package com.waitingsnow.modules.shell.view.video
{
import assets.shellView.LogoAsset;
import assets.shellView.RightControllerAsset;
import assets.shellView.ShareAsset;
import assets.shellView.playControlAsset;

import com.greensock.TweenLite;
import com.greensock.TweenMax;
import com.waitingsnow.core.debug.Logger;
import com.waitingsnow.core.display.player.SwfPlayer;
import com.waitingsnow.core.model.config.AppConfig;
import com.waitingsnow.core.util.ds.ExternalUtil;
import com.waitingsnow.modules.shell.view.video.events.PlayVideoEvent;
import com.waitingsnow.modules.shell.view.video.events.VideoEffectEvent;

import fl.controls.Button;

import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.FullScreenEvent;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.filters.GlowFilter;
import flash.utils.Timer;
import flash.utils.clearTimeout;
import flash.utils.setTimeout;

/**
 * 
 * @author waitingsnow
 * $Id: PlayVideoContainer.as 2 2012-05-17 10:10:03Z cgslendy@gmail.com $
 */
public class PlayVideoContainer extends Sprite
{
	//==========================================================================
	//  Constructor
	//==========================================================================
	/**
	 * Constructs a new <code>PlayVideoContainer</code> instance.
	 * 
	 */
	public function PlayVideoContainer()
	{
		super();
		initDisplay();
	}
	
	//==========================================================================
	//  Variables
	//==========================================================================
	private var videoSp:Sprite;
	private var playVideo:PlayVideo;
	private var sizeSp:Sprite;
	private var playControllAsset:playControlAsset;
	private var rightControllAsset:RightControllerAsset;
	private var logoAsset:LogoAsset;
	private var videoEffect:VideoEffect;
	private var shareAsset:ShareAsset;
	
	private var sizeArr:Array = [640, 960, 1280];
	private var curIndex:int = 1;
	private var sizeBtnArr:Array = [];
	private var fullFlag:Boolean;
	private var closeLightFlag:Boolean;
	private var shareArr:Array = ["tsina", "douban", "renren", "qq", "qzone", "kaixin001", "tqf"];
	private var shareMcArr:Array;
	private var countTime:Timer;
	private var intervalID:int;
	private var beginADPlayer:SwfPlayer;
	private var endADPlayer:SwfPlayer;
	
	private var videoWidth:int;
	private var videoHeight:int;
	
	//==========================================================================
	//  Properties
	//==========================================================================
	private var _startTime:Number;
	public function set startTime(value:Number):void
	{
		_startTime = value;
		
		countTime = new Timer(1000);
		countTime.addEventListener(TimerEvent.TIMER, countTimeHandler);
		countTime.start();
	}
	
	//==========================================================================
	//  Methods
	//==========================================================================
	private function initDisplay():void
	{
		videoSp = new Sprite();
		playVideo = new PlayVideo();
		playVideo.addEventListener(PlayVideoEvent.PLAY_AD_BEGIN, playADBeginHandler);
		videoSp.addChild(playVideo);
		videoSp.doubleClickEnabled = true;
		addChild(videoSp);
		addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
		//各种控制组件
		initController();
		//logo
		logoAsset = new LogoAsset();
		addChild(logoAsset);
	}
	
	private function initController():void
	{
		playControllAsset = new playControlAsset();
		playControllAsset.play_mc.addEventListener(MouseEvent.CLICK, playMcClickHandler);
		playControllAsset.set_mc.full_btn.addEventListener(MouseEvent.CLICK, fullBtnClickHandler);
		playControllAsset.set_mc.videoSet_btn.addEventListener(MouseEvent.CLICK, setBtnClickHandler);
		playControllAsset.visible = false;
		playControllAsset.alpha = 0;
		addChild(playControllAsset);
		
		rightControllAsset = new RightControllerAsset();
		createRollEvent(rightControllAsset.share_btn);
		createRollEvent(rightControllAsset.closeLight_btn);
		createRollEvent(rightControllAsset.message_btn);
		rightControllAsset.alpha = 0;
		rightControllAsset.visible = false;
		addChild(rightControllAsset);
		
		sizeSp = new Sprite();
		sizeSp.addChild(createBtn("100%"));
		sizeSp.addChild(createBtn("150%", 55));
		sizeSp.addChild(createBtn("200%", 110));
		sizeSp.y = 5;
		showCurBtnSelect();
		sizeSp.addEventListener(MouseEvent.CLICK, sizeSpClickHandler);
		sizeSp.alpha = 0;
		sizeSp.visible = false;
		addChild(sizeSp);
	}
	
	private function showVideoEffect():void
	{
		if (!videoEffect)
		{
			videoEffect = new VideoEffect();
			videoEffect.addEventListener(VideoEffectEvent.COLOR_CHANGE, colorChangeHandler);
		}
		videoEffect.x = (stage.stageWidth - videoEffect.width) * 0.5;
		videoEffect.y = (stage.stageHeight - videoEffect.height) * 0.5;
		stage.addChild(videoEffect);
	}
	
	private function createBtn(str:String, x:Number = 0, y:Number = 0, 
							   w:Number = 50, h:Number = 22):Button
	{
		var btn:Button = new Button();
		btn.label = str;
		btn.x = x;
		btn.y = y;
		btn.width = w;
		btn.height = h;
		sizeBtnArr.push(btn);
		return btn;
	}
	
	public function startPlay(streamName:String):void
	{
		playVideo.startPlay(streamName);
	}
	
	public function dispose():void
	{
		/*parent && parent.removeChild(this);*/
		playVideo.dispose();
		endPlayAD();
	}
	
	private function endPlayAD():void
	{
		Logger.log("end play AD");
		endADPlayer = new SwfPlayer();
		endADPlayer.mouseEnabled = endADPlayer.mouseChildren = false;
		endADPlayer.setSize(stage.stageWidth, stage.stageHeight - AppConfig.bottomHeight);
		endADPlayer.startPlay("./videoEnd.swf", null, true);
		addChild(endADPlayer);
	}
	
	public function setSize(width:int, height:int):void
	{
		videoWidth = width;
		videoHeight = height;
		playVideo && playVideo.setSize(videoWidth, videoHeight);
		resize();
	}
	
	public function resize(stageFlag:Boolean = false):void
	{
		var flag:Boolean = stage && stageFlag;
		var w:int = flag ? stage.stageWidth : AppConfig.swfWidth;
		var h:int = flag ? stage.stageHeight : AppConfig.swfHeight;
		h = h - AppConfig.bottomHeight;
		
		playControllAsset.bg_mc.width = w;
		playControllAsset.y = h - 24;
		playControllAsset.set_mc.x = w - playControllAsset.set_mc.width - 10;
		playControllAsset.state_txt.x = (w - 120) * 0.5;
		
		rightControllAsset.x = w - 50;
		rightControllAsset.y = (h - rightControllAsset.height) * 0.5;
		
		sizeSp.x = (w - sizeSp.width) * 0.5;
		
		graphics.clear();
		graphics.beginFill(0x00, 0);
		graphics.drawRect(0, 0, w, h);
		graphics.endFill();
		
		beginADPlayer && beginADPlayer.setSize(w, h);
		endADPlayer && endADPlayer.setSize(w, h);
		
		logoAsset.x = w - logoAsset.width - 10;
		logoAsset.y = 10;
	}
	
	private function createRollEvent(mc:MovieClip):void
	{
		mc.addEventListener(MouseEvent.ROLL_OVER, rightMcRollOverHandler);
		mc.addEventListener(MouseEvent.ROLL_OUT, rightMcRollOutHandler);
		mc.addEventListener(MouseEvent.CLICK, rightMcClickHandler);
		mc.info_txt.visible = false;
		mc.info_txt.mouseEnabled = false;
		mc.buttonMode = true;
	}
	
	private function showCurVideo(tweenFlag:Boolean = true):void
	{
		var stageW:Number = stage.stageWidth;
		var stageH:Number = stage.stageHeight;
		var w:Number = sizeArr[curIndex];
		var h:Number = sizeArr[curIndex]*9/16;
		
		if (tweenFlag)
		{
			TweenLite.to(playVideo, 1, {width:w, height:h, 
				x:(stageW-w)*0.5, y:(stageH -h - AppConfig.bottomHeight)*0.5});
		}
		else
		{
			playVideo.x = (stageW-w)*0.5;
			playVideo.y = (stageH -h - AppConfig.bottomHeight)*0.5;
			playVideo.width = w;
			playVideo.height = h;
		}
	}
	
	private function showFull():void
	{
		fullFlag = true;
		resize(true);
		sizeSp.x = (stage.stageWidth - sizeSp.width) * 0.5;
		showCurVideo(false);
		showControll();
		addChild(sizeSp);
	}
	
	private function showNormal():void
	{
		fullFlag = false;
		resize();
		sizeSp.parent && sizeSp.parent.removeChild(sizeSp);
		playVideo.x = 0;
		playVideo.y = 0;
		playVideo.setSize(videoWidth, videoHeight);
		showControll(false);
	}
	
	private function showCurBtnSelect():void
	{
		sizeBtnArr[0].filters = [];
		sizeBtnArr[1].filters = [];
		sizeBtnArr[2].filters = [];
		sizeBtnArr[curIndex].filters = [new GlowFilter()];
	}
	
	private function showControll(showFlag:Boolean = true):void
	{
		if (showFlag)
		{
			playControllAsset.visible = rightControllAsset.visible = true;
			TweenLite.to(playControllAsset, 1, {alpha:1, visible:true});
			TweenLite.to(rightControllAsset, 1, {alpha:1, visible:true});
			fullFlag && (sizeSp.visible = true);
			fullFlag && TweenLite.to(sizeSp, 1, {alpha:1, visible:true});
			clearTimeout(intervalID);
			intervalID = setTimeout(function():void
			{
				showControll(false);
			}, 3000);
		}
		else
		{
			clearTimeout(intervalID);
			TweenLite.to(playControllAsset, 1, {alpha:0, visible:false});
			TweenLite.to(rightControllAsset, 1, {alpha:0, visible:false});
			fullFlag && TweenLite.to(sizeSp, 1, {alpha:0, visible:false});
		}
	}
	
	private function showShare():void
	{
		if (!shareAsset)
		{
			shareAsset = new ShareAsset();
			shareMcArr = ["s1_btn", "s2_btn", "s3_btn", "s4_btn", "s5_btn", "s6_btn", "s7_btn"];
			shareAsset.addEventListener(MouseEvent.CLICK, shareClickHandler);
		}
		shareAsset.x = (stage.stageWidth - shareAsset.width) * 0.5;
		shareAsset.y = (stage.stageHeight - shareAsset.height) * 0.5;
		addChild(shareAsset);
	}
	
	private function showStartTime(countTime:Number):void
	{
		var hour:int = int(countTime/3600);
		var min:int = int(countTime%3600/60);
		var sec:int = int(countTime%60);
		var msg:String = getDateString(hour) + ":" + getDateString(min) + ":" + getDateString(sec);
		playControllAsset && (playControllAsset.state_txt.text = msg);
	}
	
	private function getDateString(time:Number):String
	{
		var timeStr:String = (time > 9) ? String(time) : ("0" + time);
		return timeStr;
	}
	
	//==========================================================================
	//  Event Handlers
	//==========================================================================
	private function countTimeHandler(event:TimerEvent):void
	{
		_startTime ++;
		showStartTime(_startTime);
	}
	
	private function addedToStageHandler(event:Event):void
	{
		removeEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
		stage.addEventListener(FullScreenEvent.FULL_SCREEN, fullScreenRedraw);
		doubleClickEnabled = true;
		addEventListener(MouseEvent.DOUBLE_CLICK, fullBtnClickHandler);
		addEventListener(MouseEvent.ROLL_OVER, rollOverHandler);
		addEventListener(MouseEvent.ROLL_OUT, rollOutHandler);
		addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
		resize();
	}
	
	private function shareClickHandler(event:MouseEvent):void
	{
		if (event.target.name == "cancel_btn" || 
			event.target.name == "close_btn")
		{
			shareAsset.parent && shareAsset.parent.removeChild(shareAsset);
			return;
		}
		var len:int = shareMcArr.length;
		for (var i:int = 0; i < len; i++)
		{
			if (shareMcArr[i] == event.target.name)
			{
				ExternalUtil.call(AppConfig.SHARE_TO_JS, shareArr[i]);
				break;
			}
		}
	}
	
	private function rollOverHandler(event:MouseEvent):void
	{
		showControll();
	}
	
	private function rollOutHandler(event:MouseEvent = null):void
	{
		showControll(false);
	}
	
	private function mouseMoveHandler(event:MouseEvent):void
	{
		clearTimeout(intervalID);
		playControllAsset && (playControllAsset.alpha < 1) && showControll();
	}
	
	private function rightMcRollOverHandler(event:MouseEvent):void
	{
		event.target.info_txt.visible = true;
		event.target.effect_mc.gotoAndPlay(2);
	}
	
	private function rightMcRollOutHandler(event:MouseEvent):void
	{
		event.target.info_txt.visible = false;
		event.target.effect_mc.gotoAndPlay(7);
	}
	
	private function rightMcClickHandler(event:MouseEvent):void
	{
		if (event.currentTarget.name == "share_btn")
		{
			showShare();
		}
		else if (event.currentTarget.name == "closeLight_btn")
		{
			ExternalUtil.call(AppConfig.CLOSE_LIGHT_TO_JS, int(closeLightFlag));
			closeLightFlag = !closeLightFlag;
			rightControllAsset.closeLight_btn.info_txt.text = closeLightFlag ? "开灯" : "关灯";
		}
		else if (event.currentTarget.name == "message_btn")
		{
			ExternalUtil.call(AppConfig.GOTO_MESSAGE_TO_JS);
		}
	}
	
	private function playMcClickHandler(event:MouseEvent):void
	{
		if (playVideo)
		{
			var flag:Boolean = playControllAsset.play_mc.currentFrame == 1;
			flag ? playVideo.pause() : playVideo.resume();
			playControllAsset.play_mc.gotoAndStop(flag ? 2 : 1);
		}
	}
	
	private function fullBtnClickHandler(event:MouseEvent):void
	{
		switch(stage.displayState) 
		{
			case "normal":
			{
				stage.displayState = "fullScreen";   
				break;
			}
			case "fullScreen":
			default:
			{
				stage.displayState = "normal";    
				break;
			}
		}
	}
	
	private function setBtnClickHandler(event:MouseEvent):void
	{
		showVideoEffect();
	}
	
	private function fullScreenRedraw(event:FullScreenEvent):void
	{
		if (event.fullScreen) 
		{
			showFull();
		}
		else 
		{
			showNormal();
		}
	}
	
	private function sizeSpClickHandler(event:MouseEvent):void
	{
		if (event.target == sizeBtnArr[0])
		{
			curIndex = 0;
			showCurVideo();
		}
		else if (event.target == sizeBtnArr[1])
		{
			curIndex = 1;
			showCurVideo();
		}
		else if (event.target == sizeBtnArr[2])
		{
			curIndex = 2;
			showCurVideo();
		}
		showCurBtnSelect();
	}
	
	private function colorChangeHandler(event:VideoEffectEvent):void
	{
		TweenMax.to(videoSp, 1, {colorMatrixFilter:{
			contrast:videoEffect.contrast, 
			brightness:videoEffect.brightness, 
			saturation:videoEffect.saturation, 
			hue:videoEffect.hue}});
	}
	
	private function playADBeginHandler(event:PlayVideoEvent):void
	{
		playVideo.removeEventListener(PlayVideoEvent.PLAY_AD_BEGIN, playADBeginHandler);
		if (!beginADPlayer)
		{
			Logger.log("start play AD");
			beginADPlayer = new SwfPlayer();
			beginADPlayer.startPlay("./videoStart.swf", null, true);
			beginADPlayer.setSize(stage.stageWidth, stage.stageHeight - AppConfig.bottomHeight);
			beginADPlayer.mouseEnabled = beginADPlayer.mouseChildren = false;
			beginADPlayer.addEventListener(Event.COMPLETE, 
				function beginADPlayerCompleteHandler(event:Event):void
				{
					beginADPlayer.removeEventListener(Event.COMPLETE, arguments.callee);
					beginADPlayer.parent && beginADPlayer.parent.removeChild(beginADPlayer);
					beginADPlayer.dispose();
					beginADPlayer = null;
					playVideo.stopBeginAD();
				});
			beginADPlayer.addEventListener(Event.INIT, 
				function init(event:Event):void
				{
					beginADPlayer.removeEventListener(Event.INIT, arguments.callee);
					playVideo.startBeginAD();
				});
			addChild(beginADPlayer);
		}
	}
}
}